package com.zjw.touchscreen;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.widget.*;
import androidx.annotation.RequiresApi;
import android.os.Bundle;
import com.zjw.touchscreen.config.RetrofitManager;
import com.zjw.touchscreen.db.DatabaseHelper;
import com.zjw.touchscreen.http.ApiInterface;
import com.zjw.touchscreen.http.HttpStatus;
import com.zjw.touchscreen.http.entity.CaptchaImageRespVO;
import com.zjw.touchscreen.listener.LoginListener;
import com.zjw.touchscreen.utils.UpdateUtils;
import org.apache.commons.lang3.StringUtils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.util.Base64;

public class LoginActivity extends Activity {

    private ImageView captchaCodeImage;
    private TextView captchaCodeUuid;
    private DatabaseHelper databaseHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        UpdateUtils.update(this);
        EditText userName = findViewById(R.id.userName);
        EditText password = findViewById(R.id.password);
        EditText captchaCode = findViewById(R.id.captchaCode);
        captchaCodeImage = findViewById(R.id.captchaCodeImage);
        captchaCodeUuid = findViewById(R.id.captchaCodeUuid);
        TextView toRegister = findViewById(R.id.toRegister);
        setCaptchaCodeImage(captchaCodeImage, captchaCodeUuid);
        Button loginButton = findViewById(R.id.btnLogin);
        loginButton.setOnClickListener(new LoginListener(this, userName, password, captchaCode, captchaCodeUuid));
        captchaCodeImage.setOnClickListener(v -> setCaptchaCodeImage(captchaCodeImage, captchaCodeUuid));
        toRegister.setOnClickListener(v -> startActivity(new Intent(getApplicationContext(), RegisterActivity.class)));
        databaseHelper = DatabaseHelper.getInstance(this, "touchscreen", 1);
        SQLiteDatabase readableDatabase = databaseHelper.getReadableDatabase();
        Cursor cursor = readableDatabase.rawQuery("SELECT name, pwd, token FROM user;", null);
        int count = cursor.getCount();
        if (count < 1) {
            return;
        }
        cursor.moveToFirst();
        int nameIndex = cursor.getColumnIndex("name");
        int pwdIndex = cursor.getColumnIndex("pwd");
        int tokenIndex = cursor.getColumnIndex("token");
        @SuppressLint("Range") String name = cursor.getString(nameIndex);
        @SuppressLint("Range") String pwd = cursor.getString(pwdIndex);
        @SuppressLint("Range") String token = cursor.getString(tokenIndex);
        if (StringUtils.isNotBlank(name)) {
            userName.setText(name);
        }
        if (StringUtils.isNotBlank(pwd)) {
            password.setText(pwd);
        }
    }

    public void refreshCaptchaCodeImage() {
        setCaptchaCodeImage(captchaCodeImage, captchaCodeUuid);
    }

    private void setCaptchaCodeImage(ImageView captchaCodeImage, TextView captchaCodeUuid) {
        ApiInterface apiInterface = RetrofitManager.create(ApiInterface.class);
        Call<CaptchaImageRespVO> ajaxResultCall = apiInterface.captchaImage();
        ajaxResultCall.enqueue(new Callback<CaptchaImageRespVO>() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onResponse(Call<CaptchaImageRespVO> call, Response<CaptchaImageRespVO> response) {
                CaptchaImageRespVO body = response.body();
                if (HttpStatus.SUCCESS != response.code()) {
                    Toast.makeText(getApplicationContext(), "获取验证码图片失败!", Toast.LENGTH_SHORT).show();
                    return;
                }
                String uuid = body.getUuid();
                String imgStr = body.getImg();
                byte[] imageData = Base64.getDecoder().decode(imgStr);
                captchaCodeUuid.setText(uuid);
                captchaCodeImage.setImageBitmap(BitmapFactory.decodeByteArray(imageData, 0, imageData.length));
            }

            @Override
            public void onFailure(Call<CaptchaImageRespVO> call, Throwable throwable) {
                Toast.makeText(getApplicationContext(), "获取验证码图片失败!", Toast.LENGTH_SHORT).show();
            }
        });
    }
}